package edu.bu.bga;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import edu.bu.bga.db.DatabaseHelper;

public class DeleteRuleActivity extends ListActivity implements
		OnItemClickListener {

	private Button backButton;
	private AlertDialog.Builder builder;
	private DatabaseHelper dbHelper;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.delete_list);

		backButton = (Button) this.findViewById(R.id.backbutton);
		backButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

		dbHelper = new DatabaseHelper(getApplicationContext());

		Cursor rulersCursor = dbHelper.getAllRulesCursor();

		String[] displayFields = { "t_Rules_Text" };
		setListAdapter(new SimpleCursorAdapter(this,
				android.R.layout.simple_list_item_1, rulersCursor,
				displayFields, new int[] { android.R.id.text1 }));

		ListView list = getListView();
		list.setOnItemClickListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			final long id) {
		Log.i(this.getClass().getSimpleName(), "ID = " + id);

		builder = new AlertDialog.Builder(this);

		builder.setMessage("Are you sure?")
				.setPositiveButton(android.R.string.yes,
						new Dialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								dbHelper.deleteRule(Long.toString(id));

								Toast.makeText(DeleteRuleActivity.this,
										"Deleted rule", Toast.LENGTH_SHORT);
								finish();
							}
						})
				.setNegativeButton(android.R.string.no,
						new Dialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();

							}
						});
		builder.show();
	}
}
